
#include <Arduino.h>
#include <DHT11.h>
#define _pin 15

static uint8_t dht11_readByte() {
  uint8_t value = 0;
  int8_t i = 0;

  for (i = 0; i < 8; i++) {
    while (digitalRead(_pin) == LOW)
      ;
    delayMicroseconds(30);
    if (digitalRead(_pin) == HIGH) {
      value |= (1 << (7 - i));
    }
    while (digitalRead(_pin) == HIGH)
      ;
  }

  return value;
}
static bool dht11_startSignal() {
  pinMode(_pin, OUTPUT);
  digitalWrite(_pin, 1);
  delay(100);

  // begin
  digitalWrite(_pin, 0);
  delay(25);

  digitalWrite(_pin, 1);

  delayMicroseconds(30);
  pinMode(_pin, INPUT);

  return digitalRead(_pin) == LOW;
}

static int8_t dht11_readRawData(uint8_t *dat) {
  int8_t i = 0;
  delay(500);

  if (dht11_startSignal()) {
    while (digitalRead(_pin) == LOW)  // Wait pull up
      ;
    if (digitalRead(_pin) == HIGH) {
      while (digitalRead(_pin) == HIGH)
        ;
      for (i = 0; i < 5; i++)
        dat[i] = dht11_readByte();
    }

    Serial.println("Send sucessfully");
  } else
    Serial.println("Dht start signal send failed");

  return -1;
}


//DHT11 dht11(15);
void check_DHT11() {
  delay(500);
  pinMode(_pin, OUTPUT);
  digitalWrite(_pin, 1);
  delay(25);

  digitalWrite(_pin, 0);
  delay(25);
  digitalWrite(15, 1);

  pinMode(15, INPUT);
  delayMicroseconds(30);

  if (digitalRead(_pin) == LOW) {
    Serial.println("Exist the model");
  } else {

    Serial.println("NOT Exist the model");
  }
}

DHT11 dht11(_pin);

void setup() {

  Serial.begin(115200);

  pinMode(15, OUTPUT);
}

void loop() {
  uint8_t data[5];

  dht11_readRawData(data);
  check_DHT11();
  for (int i = 0; i < 5; i++)
    Serial.printf("dat[%d] = %d\n", i, data[i]);

  int temp, humi;
  dht11.readTemperatureHumidity(temp, humi);
  Serial.printf("T = %d ,H = %d\n",temp,humi);


  delay(1000);
  // // Attempt to read the temperature value from the DHT11 sensor.
  // int temperature = dht11.readTemperature();
  // int humi=dht11.readHumidity();

  // // Check the result of the reading.
  // // If there's no error, print the temperature value.
  // // If there's an error, print the appropriate error message.
  // if (temperature != DHT11::ERROR_CHECKSUM && temperature != DHT11::ERROR_TIMEOUT) {
  //     Serial.print("Temperature: ");
  //     Serial.print(temperature);
  //     Serial.println(" °C");
  //     Serial.printf("Huminity :%d %\n",humi);
  // } else {
  //     // Print error message based on the error code.
  //     Serial.println(DHT11::getErrorString(temperature));
  // }
}
